var editor_objects = [];
var current_object = false;
var current_selection = false;

$(function()
{
	$('#form-editor').submit(function()
	{
		for (var i=0; i<editor_objects.length; i++)
		{
			var format = editor_objects[i].data('format');
			
			$(this).append($('<input type="hidden" name="id[]" />').val(format.id));
			$(this).append($('<input type="hidden" name="type[' + format.id + ']" />').val(format.type));
			$(this).append($('<input type="hidden" name="x[' + format.id + ']" />').val(format.x));
			$(this).append($('<input type="hidden" name="y[' + format.id + ']" />').val(format.y));
			$(this).append($('<input type="hidden" name="width[' + format.id + ']" />').val(format.width));
			$(this).append($('<input type="hidden" name="height[' + format.id + ']" />').val(format.height));			
			
			if ('text' == format.type)
			{
				$(this).append($('<input type="hidden" name="font[' + format.id + ']" />').val(format.font));
				$(this).append($('<input type="hidden" name="fontsize[' + format.id + ']" />').val(format.fontsize));
				$(this).append($('<input type="hidden" name="fontsizecustom[' + format.id + ']" />').val(format.fontsizecustom));
				$(this).append($('<input type="hidden" name="color[' + format.id + '][r]" />').val(format.color.r));
				$(this).append($('<input type="hidden" name="color[' + format.id + '][g]" />').val(format.color.g));
				$(this).append($('<input type="hidden" name="color[' + format.id + '][b]" />').val(format.color.b));
				
				if (format.bgcolor)
				{
					$(this).append($('<input type="hidden" name="bgcolor[' + format.id + '][r]" />').val(format.bgcolor));
					$(this).append($('<input type="hidden" name="bgcolor[' + format.id + '][g]" />').val(format.bgcolor));
					$(this).append($('<input type="hidden" name="bgcolor[' + format.id + '][b]" />').val(format.bgcolor));
				}
				
				$(this).append($('<input type="hidden" name="bold[' + format.id + ']" />').val(format.bold));
				$(this).append($('<input type="hidden" name="italic[' + format.id + ']" />').val(format.italic));
				$(this).append($('<input type="hidden" name="underline[' + format.id + ']" />').val(format.underline));
				$(this).append($('<input type="hidden" name="strikethrough[' + format.id + ']" />').val(format.strikethrough));
				$(this).append($('<input type="hidden" name="align[' + format.id + ']" />').val(format.align));
				$(this).append($('<input type="hidden" name="text[' + format.id + ']" />').val(format.text));
			}
			else if ('image' == format.type)
			{
				$(this).append($('<input type="hidden" name="src[' + format.id + ']" />').val(format.src));
			}
			
		}
	});
	
	// editor buttons handlers
	
	$('#image').uploadify({ 
		wmode: 'transparent',
		uploader:  '/swf/uploadify.swf',
		script:    '/editor/imgupload',
		auto: true, 
		fileDataName: 'image',
//		buttonText: 'Add Image',
		buttonImg:    '/i/editor/addimage.gif',
//		hideButton: true,
		fileDesc : 'Image files (*.jpg, *.gif, *.png)',
		fileExt : '*.jpg;*.gif;*.png',
		cancelImg: '/i/cancel.png',
		onComplete : imageUploadComplete,
		onError: imageUploadError
	});
	
	$('#bgimage').uploadify({ 
		uploader:  '/swf/uploadify.swf', 
		script:    '/editor/imgupload', 
		auto: true,
		fileDataName: 'image',
//		buttonText: 'Change BG Image',
		buttonImg:    '/i/editor/addbgimage.gif',
		fileDesc : 'Image files (*.jpg, *.gif, *.png)',
		fileExt : '*.jpg;*.gif;*.png',
		cancelImg: '/i/cancel.png',
		onComplete : bgimageUploadComplete
	});	

	$('#add-text').click(function()
	{
		var text = 'Text template ' + Math.random();
		var obj = $('<div class="editor-item text-block"><span>' + text + '</span></div>');
		
		obj.data('format', {
				id: uniqueId(),
				type: 'text',
				x: 0,
				y: 0,
				text: text,
				font: obj.css('font-family'),
				fontsize: obj.css('font-size'),
				fontsizecustom: '',
//				color: obj.css('color'),
				color: {r: 0, g: 0, b: 0},
//				bgcolor: obj.css('background-color'),
				bgcolor: false,
				bold: false,
				italic: false,
				underline: false,
				strikethrough: false,
				align: obj.css('text-align'),
				width: obj.css('width'),
				height: obj.css('height')
		});

		obj.click(function()
		{
			initEditor($(this));
		});

		$('#editor').append(obj);
		
		editor_objects.push(obj);
		initEditor(obj);
	});

	$('#text-color').ColorPicker({color: '#000000', onChange: setColor});
	$('#background-color').ColorPicker({color: '#ffffff', onChange: setBackgroundColor});
	
	$('#text-font-family').change(function()
	{
		current_object.css('font-family', $(this).val());
		
		// save format
		var format = current_object.data('format');
		format.font = $(this).val();
		current_object.data('format', format);		
	});

	$('#text-font-size').change(function()
	{
		current_object.css('font-size', $(this).val());
		current_object.css('line-height', $(this).val());
		
		// clear custom font size field
		$('#text-font-size-custom').val('');
		
		// save format
		var format = current_object.data('format');
		format.fontsize = $(this).val();
		format.fontsizecustom = '';
		current_object.data('format', format);		
	});
	
	$('#text-font-size-custom').keyup(function()
	{
		current_object.css('font-size', $(this).val() + 'px');
		current_object.css('line-height', $(this).val() + 'px');
		
		// save format
		var format = current_object.data('format');
		format.fontsizecustom = $(this).val();
		current_object.data('format', format);		
	});	

	$('#text-bold').click(function()
	{
		var format = current_object.data('format');
		
		if ($(this).hasClass('button-active'))
		{
			current_object.css('font-weight', 'normal');
			$(this).removeClass('button-active');
			format.bold = false;
		}
		else
		{
			current_object.css('font-weight', 'bold');
			$(this).addClass('button-active');
			format.bold = true;
		}
		
		current_object.data('format', format);		
	});

	$('#text-italic').click(function()
	{
		var format = current_object.data('format');
		
		if ($(this).hasClass('button-active'))
		{
			current_object.css('font-style', 'normal');
			$(this).removeClass('button-active');
			format.italic = false;
		}
		else
		{
			current_object.css('font-style', 'italic');
			$(this).addClass('button-active');
			format.italic = true;
		}
		
		current_object.data('format', format);
	});

	$('#text-underline').click(function()
	{
		var format = current_object.data('format');
		
		if ($(this).hasClass('button-active'))
		{
			current_object.css('text-decoration', 'none');
			$(this).removeClass('button-active');
			format.underline = false;
		}
		else
		{
			current_object.css('text-decoration', 'underline');
			$(this).addClass('button-active');
			format.underline = true;
		}
		
		current_object.data('format', format);
	});

	$('#text-strikethrough').click(function()
	{
		var format = current_object.data('format');
		
		if ($(this).hasClass('button-active'))
		{
			current_object.css('text-decoration', 'none');
			$(this).removeClass('button-active');
			format.strikethrough = false;
		}
		else
		{
			current_object.css('text-decoration', 'line-through');
			$(this).addClass('button-active');
			format.strikethrough = true;
		}
		
		current_object.data('format', format);
	});

	$('#text-align-left').click(function()
	{
		current_object.css('text-align', 'left');
		
		var format = current_object.data('format');
		format.align = 'left';
		current_object.data('format', format);		

		$(this).attr('disabled', 'disabled');
		$('#text-align-right').attr('disabled', '');
		$('#text-align-center').attr('disabled', '');
		$('#text-align-justify').attr('disabled', '');
	});

	$('#text-align-right').click(function()
	{
		current_object.css('text-align', 'right');
		
		var format = current_object.data('format');
		format.align = 'right';
		current_object.data('format', format);		

		$(this).attr('disabled', 'disabled');
		$('#text-align-left').attr('disabled', '');
		$('#text-align-center').attr('disabled', '');
		$('#text-align-justify').attr('disabled', '');
	});

	$('#text-align-center').click(function()
	{
		current_object.css('text-align', 'center');
		
		var format = current_object.data('format');
		format.align = 'center';
		current_object.data('format', format);

		$(this).attr('disabled', 'disabled');
		$('#text-align-left').attr('disabled', '');
		$('#text-align-right').attr('disabled', '');
		$('#text-align-justify').attr('disabled', '');
	});

	$('#text-align-justify').click(function()
	{
		current_object.css('text-align', 'justify');
		
		var format = current_object.data('format');
		format.align = 'justify';
		current_object.data('format', format);		

		$(this).attr('disabled', 'disabled');
		$('#text-align-left').attr('disabled', '');
		$('#text-align-right').attr('disabled', '');
		$('#text-align-center').attr('disabled', '');
	});

	$('#text-content').keyup(function()
	{
		var value = $(this).val();
		current_object.find('span').text(value);
		
		// save format
		var format = current_object.data('format');
		format.text = value;
		current_object.data('format', format);
	});
	
	$('#image-crop').click(function()
	{
		current_object.draggable('destroy');
		
		current_object.imgAreaSelect({
			handles: true,
			onInit: setCropParams,
			onSelectEnd: setCropParams
		});
		
		$('#apply-crop').show();
		$('#cancel-crop').show();
	});	
	
	$('#apply-crop').click(function()
	{
		doCrop();
	});	
	
	$('#cancel-crop').click(function()
	{
		removeCrop();
	});
	
	$('#delete-object').click(function()
	{
		var id = current_object.data('format').id;
		
		for (var i=0; i<editor_objects.length; i++)
		{
			if (editor_objects[i].data('format').id == id)
			{
				current_object.remove();
				editor_objects.splice(i, 1);
			}
		}
		
		disableButtons();
		current_object = false;
		$(this).attr('disabled', 'disabled');
	});
});

function setCropParams(image, selection)
{
	current_selection = selection;
	$('#apply-crop').attr('disabled', (selection.x1 != selection.x2 && selection.y1 != selection.y2) ? '' : 'disabled');
}

function doCrop()
{
	$.ajax(
	{
		type: 'POST',
		url: '/editor/crop',
		data: {
			'image' : current_object.data('format').src,
			'x'    : current_selection.x1,
			'y'    : current_selection.y1,
			'width'    : current_selection.width,
			'height'    : current_selection.height
		},
		dataType: 'json',
		success: cropSuccess
	});		
}

function cropSuccess(response)
{
	current_object.attr('src', response.file);
	
	var format = current_object.data('format');
	
	current_object.css('left', format.x + current_selection.x1 + 'px');
	current_object.css('top', format.y + current_selection.y1 + 'px');	
	
	format.src = response.file;
	current_object.data('format', format);
	
	removeCrop();
}

function removeCrop()
{
	current_object.imgAreaSelect({remove: true});
	addDraggable(current_object);
	$('#apply-crop').hide();
	$('#cancel-crop').hide();
}

function imageUploadComplete(event, queueId, fileObj, response, data)
{
	eval('response = ' + response);
	if (undefined != response.status && response.status)
	{
		addImage(response.file);
	}
	else
	{
		alert(response.error);
	}
}

function imageUploadError()
{
	alert('image upload error');
}

function bgimageUploadComplete(event, queueId, fileObj, response, data)
{
	eval('response = ' + response);
	if (undefined != response.status && response.status)
	{
		addBgImage(response.file);
	}
}

function setColor(hsb, hex, rgb)
{
	current_object.css('color', '#' + hex);
	
	// save format
	var format = current_object.data('format');
	format.color = rgb;
	current_object.data('format', format);
}

function setBackgroundColor(hsb, hex, rgb)
{
	current_object.css('background-color', '#' + hex);
	
	// save format
	var format = current_object.data('format');
	format.bgcolor = rgb;
	current_object.data('format', format);	
}

function onDragStop(event, ui)
{
	// save format
	var format = current_object.data('format');
	format.x = ui.position.left;
	format.y = ui.position.top;
	current_object.data('format', format);
}

function onResizeStop(event, ui)
{
	// save format
	var format = current_object.data('format');
	format.width = ui.size.width;
	format.height = ui.size.height;
	current_object.data('format', format);	
}

function initEditor(obj)
{
	current_object = obj;
	
	$('#delete-object').attr('disabled', '');
	
	var format = obj.data('format');	
	
	for (var i=0; i<editor_objects.length; i++)
	{
		if (editor_objects[i].data('format').id == format.id)
		{
			editor_objects[i].addClass('item-active');
			addDraggable(obj);
			if ('text' == format.type)
				obj.resizable({containment : 'parent', stop: onResizeStop});
		}
		else
		{
			editor_objects[i].removeClass('item-active');
			editor_objects[i].draggable('destroy');
			if ('text' == format.type)
				editor_objects[i].resizable('destroy');
		}
	}
	
	initButtons(format.type);
	
	if ('text' == format.type)
	{
		$('#text-content').val(obj.text());
		
		$('#text-font-family option').each(function()
		{
			obj = $(this);
			if (obj.val() == format.font)
			{
				obj.attr('selected', 'selected');
			}
		});
		
		$('#text-font-size option').each(function()
		{
			obj = $(this);
			if (obj.val() == format.fontsize)
			{
				obj.attr('selected', 'selected');
			}
		});
		
		$('#text-font-size-custom').val(format.fontsizecustom);
		
		$('#text-color').ColorPickerSetColor(format.color);
		$('#background-color').ColorPickerSetColor(format.bgcolor);		
		
		if (format.bold)
			$('#text-bold').addClass('button-active');
		
		if (format.italic)
			$('#text-italic').addClass('button-active');
		
		if (format.underline)
			$('#text-underline').addClass('button-active');
		
		if (format.strikethrough)
			$('#text-strikethrough').addClass('button-active');
		
		initTextAlignButtons(format.align);
	}
	
//	else if ('image' == format.type)
//	{
//		$('#text-content').val('');
//	}
}

function addDraggable(obj)
{
	obj.draggable({containment : 'parent', stop: onDragStop, stack: {group: '.editor-item', min: 10}});
}

function initButtons(type)
{
	disableButtons();
	
	if ('text' == type)
	{
		$('#text-controls input').attr('disabled', '');
		$('#text-controls select').attr('disabled', '');
		$('#text-controls button').attr('disabled', '');
		$('#text-controls textarea').attr('disabled', '');
		
		$('#text-color').removeClass('disabled');
		$('#background-color').removeClass('disabled');
		$('#text-bold').removeClass('disabled');
		$('#text-italic').removeClass('disabled');
		$('#text-underline').removeClass('disabled');
		$('#text-strikethrough').removeClass('disabled');
		$('#text-align-left').removeClass('disabled');
		$('#text-align-right').removeClass('disabled');
		$('#text-align-center').removeClass('disabled');
		$('#text-align-justify').removeClass('disabled');
	}
	
	if ('image' == type)
	{
		$('#image-controls button').attr('disabled', '').removeClass('disabled')
	}
}

function disableButtons()
{
	$('#text-controls input').attr('disabled', 'disabled');
	$('#text-controls select').attr('disabled', 'disabled');
	$('#text-controls button').attr('disabled', 'disabled').removeClass('button-active');
	$('#image-controls button').attr('disabled', 'disabled');
	$('#image-controls textarea').attr('disabled', 'disabled');
	
	$('#image-controls button').addClass('disabled');
	
	$('#text-content').attr('disabled', 'disabled');
	$('#text-color').addClass('disabled');
	$('#background-color').addClass('disabled');
	$('#text-bold').addClass('disabled');
	$('#text-italic').addClass('disabled');
	$('#text-underline').addClass('disabled');
	$('#text-strikethrough').addClass('disabled');
	$('#text-align-left').addClass('disabled');
	$('#text-align-right').addClass('disabled');
	$('#text-align-center').addClass('disabled');
	$('#text-align-justify').addClass('disabled');
	
	$('#text-content').val('');
}
	
function initTextAlignButtons(currentButton)
{
	var buttons = ['text-align-left', 'text-align-right', 'text-align-center', 'text-align-justify'];
	
	currentButton = 'text-align-' + currentButton;
	
	for (var i=0; i<buttons.length; i++)
	{
		$('#' + buttons[i]).attr('disabled', (currentButton == buttons[i] ? 'disabled' : ''));
	}
}

function addImage(src)
{
	var obj = $('<img class="editor-item image-block" src="' + src + '" />');
	
	obj.data('format', {
		id: uniqueId(),
		type: 'image',
		src: src,
		x: 0,
		y: 0,
		width: obj.attr('width'),
		height: obj.attr('height')
	});

	obj.click(function()
	{
		initEditor($(this));
	});

	addDraggable(obj);
	$('#editor').append(obj);
	
	editor_objects.push(obj);
	initEditor(obj);
}

function addBgImage(src)
{
	$('#editor').css('background', 'url(' + src + ') no-repeat');
}

function uniqueId()
{
	var date = new Date;
	return date.getTime();
}

function rgbToHex(rgb)
{
	var rgbvals = /rgb\((.+),(.+),(.+)\)/i.exec(rgb);
	var rval = parseInt(rgbvals[1]);
	var gval = parseInt(rgbvals[2]);
	var bval = parseInt(rgbvals[3]);
	return '#' + (
		rval.toString(16) +
		gval.toString(16) +
		bval.toString(16)
	);
} 

function hex(c)
{
	var m = /rgba?\((\d+), (\d+), (\d+)/.exec(c);
	return m ? '#' + ( m[1] << 16 | m[2] << 8 | m[3] ).toString(16) : c;
}